package ipebg.mzk.common.util;

import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.w3c.dom.Document;
import org.w3c.dom.Node;

/**
 * Created by LT on 2016/3/16.
 */
public class DomUtil {
    private static DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    private static DocumentBuilder builder = null;

    public static DocumentBuilder createBuilder() {
        if (builder == null) {
            try {
                return builderFactory.newDocumentBuilder();
            } catch (ParserConfigurationException e) {
                e.printStackTrace();
            }
        }
        return builder;
    }

    public static Document buildDoc(String str) {
        builder = createBuilder();
        str = fitration(str);
        InputStream is=null;
        try {
            is = new ByteArrayInputStream(str.getBytes("utf-8"));
            return builder.parse(is);
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public static String getFirstNodeTextContentByTagName(Document doc,String tagName) {
        Node node = getFirstNodeByTagName(doc,tagName);
        if (node != null) {
            return node.getAttributes().toString();// node.getTextContent();
        }
        return null;
    }

    public static Node getFirstNodeByTagName(Document doc, String tagName) {
        NodeList nodeList = doc.getElementsByTagName(tagName);
        if (nodeList != null && nodeList.getLength() > 0) {
            return nodeList.item(0);
        }
        return null;
    }

    public static String fitration(String string) {
        String regEx="[&]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(string);
        return m.replaceAll("").trim();
    }
}
